<?php


namespace app\service\model;


use app\service\Token;

class GoodsActivityModel extends BaseModel
{

    protected $table = 'goods_activity';

    /**
     * 获取商品最优惠的活动
     * @param $id
     * @return array|mixed
     * @throws \app\service\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getActivity($id)
    {
        $datetime = date('Y-m-d H:i:s');
        $activity_list = ActivityModel::where('start_time', '<', $datetime)
            ->where('end_time', '>', $datetime)
            ->order('discount', 'asc')
            ->select();
        $activity = [];
        foreach ($activity_list as $a) {
            if ($a->scope == 2) {
                // 不限次数
                $activity = $a;
            } else {
                $goods_activity = self::where('activity_id', '=', $a->id)
                    ->where('goods_id', '=', $id)->find();
                if ($goods_activity) {
                    if (request()->header('token')) {
                        $member = Token::checkMemberToken();
                        // 如果用户已登录，且活动有限制参与次数，则检查用户已参与次数
                        if ($a->allowvote_num > 0) {
                            $member_allowvote_num = GoodsActivityMemberModel::where('member_id', '=', $member->id)
                                ->where('activity_id', '=', $a->id)
                                ->where('goods_id', '=', $id)
                                ->count();
                            if ($member_allowvote_num < $a->allowvote_num) {
                                $activity = $a;
                            }
                        }
                    } else {
                        $activity = $a;
                    }
                }
            }

            // 找到最优惠的活动，跳出循环
            if ($activity) {
                break;
            }
        }

        return $activity;
    }
}